# -*- coding:utf-8 -*-
from server.mongodb import mongo
from twisted.internet import defer
import time

log_summary = {
    "connectionLost": "Lost connection......",
    "connectionMade": "Connection has benn make",
    "dataReceived": "Data received",
    "send_Data": "Has send data",
    "unSendData": "Message have not send",
    "unLegitimate": "Error happen",
    "select": "DB [select]",
    "insert": "DB [insert]",
    "update": "DB [update]",
    "delete": "DB [delete]"
}
# log_message = {
#     "connectionMade": "None",
#     "dataReceived": "%r"
# }


mongo = mongo('mongodb://127.0.0.1')


def logged(when):
    def log(*args, **kargs):
        date = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())  # 当前时间
        summary = log_summary[kargs['func'].func_name]  # 方法概述
        context = kargs['context']  # 上下文
        message = ''
        if len(args) > 1:
            for each in xrange(1, len(args)):
                message += str(args[each]) + '\n'  # 数据（如果有的话）

        return {
            "time": date,
            "summary": summary,
            "context": context,
            "message": message,
        }

    def debug_logged(func):
        def wrapper(*args, **kargs):
            d = defer.Deferred()
            d.addCallback(mongo.insert)
            log_data = log(*args, func=func, context=None)

            d.callback(("debug", log_data))

            return func(*args, **kargs)

        return wrapper

    def info_logged(func):
        def wrapper(*args, **kargs):
            d = defer.Deferred()
            d.addCallback(mongo.insert)
            context = args[0].transport.getPeer()
            log_data = log(*args, func=func, context=str(context))

            d.callback(("info", log_data))

            return func(*args, **kargs)

        return wrapper

    def warn_logged(func):
        def wrapper(*args, **kargs):
            d = defer.Deferred()
            d.addCallback(mongo.insert)
            context = None
            log_data = log(*args, func=func, context=str(context))

            d.callback(("warn", log_data))
            return func(*args, **kargs)

        return wrapper

    def error_logged(func):
        def wrapper(*args, **kargs):
            pass
            return func(*args, **kargs)

        return wrapper

    try:
        return {"INFO": info_logged,
                "DEBUG": debug_logged,
                "WARN": warn_logged,
                "ERROR": error_logged}[when]
    except Exception, e:
        return error_logged(e)

